<template>
  <div id="map-container" />
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader' // 按需引入依赖
// import { on } from "events";
window._AMapSecurityConfig = {
  securityJsCode: '57a18aafb55064088272e9831ab8aa35' // 安全密钥
}
export default {
  props: {
    longitude: {
      default: 113.616029,
      type: Number
      // 经度
    },
    latitude: {
      default: 34.75,
      type: Number
    }, // 纬度
    inputStr: {
      default: '',
      type: String
    }
  },
  data() {
    return {
      map: null,
      mouseTool: null,
      overlays: [],
      auto: null,
      placeSearch: null,
      marker: null,
      address: '',
      markers: [],
      markerList: []
    }
  },
  mounted() {
    this.initMap()
  },
  beforeDestroy() {
    this.map?.destroy()
  },
  methods: {
    // 初始化地图
    initMap() {
      const centerLen = [this.longitude, this.latitude]
      AMapLoader.load({
        'key': '7ce880f2976149e9e8f24e51b0c34084', // 申请好的Web端开发者Key，首次调用 load 时必填
        'version': '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        'plugins': ['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar', 'AMap.MouseTool', 'AMap.MapType', 'AMap.HawkEye', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map('map-container', {
            viewMode: '3D', //  是否为3D地图模式
            zoom: 15, // 初始化地图级别
            center: [this.longitude, this.latitude], // 中心点坐标  郑州
            resizeEnable: true,
            zoomEnable: true
          })
          this.setMarker(centerLen, AMap)
          // 鼠标点击获取经纬度
          this.map.on('click', (e) => {
            console.log('e---', e)
            console.log('e.lnglat---', e.lnglat)
            console.log('经度', e.lnglat.getLng())
            console.log('纬度', e.lnglat.getLat())
            this.$emit('update:longitude', e.lnglat.getLng())
            this.$emit('update:latitude', e.lnglat.getLat())
            const lnglat = e.lnglat // 获取点击位置的经纬度
            this.setMarker([e.lnglat.getLng(), e.lnglat.getLat()], AMap)
            // 设置新的中心点
            this.map.setCenter(lnglat)
            // 点击地图上的位置，根据经纬度转换成详细地址
            const geocoder = new AMap.Geocoder({})
            const that = this
            geocoder.getAddress([e.lnglat.getLng(), e.lnglat.getLat()], function(status, result) {
              if (status === 'complete' && result.regeocode) {
                that.address = result.regeocode.formattedAddress
                that.$emit('update:inputStr', that.address)
                console.log(that.address, '位置信息')
              } else {
                //
              }
            })
          })

          // 地图上绘制点位
          this.mouseTool = new AMap.MouseTool(this.map)
          // 监听draw事件可获取画好的覆盖物
          this.mouseTool.on('draw', function(e) {
            console.log('获取画好的覆盖物', e)
            this.overlays.push(e.obj)
          }.bind(this))
          this.searchMap(AMap, this.inputStr)
          // AMap.event.addListener(this.placeSearch, 'markerClick', function(e) {
          //   // railCenter = [e.data.location.lng, e.data.location.lat]
          //   console.log(e, '点击')
          // })
          this.markerList = new AMap.MarkerList()
          console.log(this.markerList, 'markerList')
        }).catch(e => {
          console.log(e)
        })
    },
    // 具体画图代码
    draw(type) {
      switch (type) {
        case 'marker': {
          this.mouseTool.marker({
            // 同Marker的Option设置
          })
          break
        }
        case 'polyline': {
          this.mouseTool.polyline({
            strokeColor: '#80d8ff'
            // 同Polyline的Option设置
          })
          break
        }
        case 'polygon': {
          this.mouseTool.polygon({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            // 同Polygon的Option设置
          })
          break
        }
        case 'rectangle': {
          this.mouseTool.rectangle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            // 同Polygon的Option设置
          })
          break
        }
        case 'circle': {
          this.mouseTool.circle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            // 同Circle的Option设置
          })
          break
        }
      }
    },
    //  添加标记
    setMarker(lnglat, AMap) {
      this.removeMarker()
      const marker = new AMap.Marker({
        position: lnglat
      })
      marker.setMap(this.map)
      this.markers.push(marker)
      // 鼠标点击marker触发
      // marker.on('click', function(e) {
      //   // this.openCar(item) //
      //   console.log(e, 'e')
      // })
    },
    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers)
      }
    },
    searchMap(AMap) {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: 'tipinput' // 使用联想输入的input的id
      })
      // 构造地点查询类
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
        pageSize: 1
        // panel: 'panel'
      })
      console.log(this.placeSearch, 'placeSearch')
      // 当选中某条搜索记录时触发
      this.auto.on('select', (e) => {
        if (e.poi.location) {
          console.log(e)
          // this.lnglat = [e.poi.location.lng, e.poi.location.lat];
          this.placeSearch.setCity(e.poi.adcode)
          this.placeSearch.search(e.poi.name) // 关键字查询
          const geocoder = new AMap.Geocoder({})
          const that = this
          that.$emit('update:longitude', e.poi.location.lng)
          that.$emit('update:latitude', e.poi.location.lat)
          that.setMarker([this.longitude, this.latitude], AMap)

          geocoder.getAddress([e.poi.location.lng, e.poi.location.lat], function(status, result) {
            console.log(11111111, status, result)
            if (status === 'complete' && result.regeocode) {
              // that.$emit('update:longitude', e.poi.location.lng)
              // that.$emit('update:latitude', e.poi.location.lat)
              that.setMarker([that.longitude, that.latitude], AMap)
              // 自己想要赋的值，根据自己的做修改
              that.$emit('update:inputStr', e.poi.name)
            } else {
            //
            }
          })
        } else {
          this.$message.error('查询地址失败，请重新输入地址')
        }
      })
      // AMap.event.addListener(this.placeSearch, 'markerClick', (e) => {
      //   var infoWindow = new AMap.InfoWindow({
      //     content: '<h3>' + e.target.getTitle() + '</h3><p>' + e.target.getAdcode() + '</p>'
      //   })
      //   infoWindow.open(this.map, e.target.GeolocationPosition())
      //   console.log('Marker clicked')
      // })
    }
  }
}
</script>

<style scoped>
#map-container {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0;
}
</style>
